import 'dart:async';
import 'package:flutter/material.dart';

///动画列表
class AnimatedListPage extends StatefulWidget {
  const AnimatedListPage({super.key});

  @override
  State<AnimatedListPage> createState() => _AnimatedListPageState();
}

class _AnimatedListPageState extends State<AnimatedListPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AnimatedList')),
      body: AnimatedHomePage(),
    );
  }
}

class AnimatedHomePage extends StatefulWidget {
  const AnimatedHomePage({super.key});

  @override
  State<AnimatedHomePage> createState() => _AnimatedHomePageState();
}

class _AnimatedHomePageState extends State<AnimatedHomePage> {
  final _globalKey = GlobalKey<AnimatedListState>();
  bool flag=true;
  List<String> list = ["第一条", "第二条", "第三条", "第四条", "第五条"];

  //定义创建方法
  Widget _buildItem(int index) {
    return ListTile(
      key:ValueKey(index),
      title: Text(list[index]),
      trailing: IconButton(icon: Icon(Icons.delete),onPressed: (){
        _deleteItem(index);
      },),
    );
  }

  _deleteItem(int index) {
      print("删除索引`$index`");
      if(flag==true){
        flag=false;
        _globalKey.currentState!.removeItem(index, (context, animation) {
          var returnWidget = _buildItem(index);
          list.removeAt(index);
          return ScaleTransition(
            //opacity: animation,
            scale: animation,
            child: returnWidget,
          );
        });
        Timer.periodic(Duration(milliseconds: 500), (timer) {
          flag=true;
          timer.cancel();
        });
      }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          list.add("第${list.length - 1}条");
          _globalKey.currentState!.insertItem(list.length - 1); // 插入新项
        },
      ),
      body: AnimatedList(
        key: _globalKey,
        initialItemCount: list.length,
        itemBuilder: (context, index, animation) {
          return FadeTransition(
            opacity: animation,
            child: _buildItem(index),
          );
        },
      ),
    );
  }
}
